<template>
  <a-modal
    :open="props.modelVisible"
    title="成员管理"
    :destroyOnClose="true"
    @cancel="handleCancel"
    @ok="handleOk"
    width="710px"
  >
    <div class="container">
      <div style="width: 45%">
        <a-form-item name="members" label="选择成员">
          <a-select
            v-model:value="formState.members"
            mode="multiple"
            placeholder="请选择项目成员"
            :field-names="{ label: 'userName', value: 'userId' }"
            :options="items"
            :loading="loading"
            style="width: 100%"
            :listHeight="400"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <a-space style="display: flex; justify-content: center">
                <a-input 
                  v-model:value="searchInput" 
                  placeholder="搜索成员"
                  allow-clear 
                  @change="searchUser"
                  @pressEnter="searchUser"
                />
                <a-segmented v-model:value="searchType" :options="searchTypes" />
              </a-space>
              <a-divider style="margin: 4px 0" />
              <v-nodes :vnodes="menu" />
            </template>
          </a-select>
        </a-form-item>
      </div>

      <a-divider type="vertical" style="height: 100%" />
      <div style="width: 45%">
        <div style="margin-top: 10px">已选择 · {{ selectedDate.length }}</div>
        <a-list style="height: 85%; overflow-y: auto; margin-top: 10px" :data-source="selectedDate">
          <template #renderItem="{ item }">
            <a-list-item class="item">
              <span> {{ item.userName }}</span>
              <a-select
                ref="select"
                v-model:value="item.type"
                style="width: 120px"
                :bordered="false"
                :disabled="item.userId === store.getters.projectCreatorId"
                :showArrow="!(item.userId === store.getters.projectCreatorId)"
              >
                <a-select-option :value="0">负责人</a-select-option>
                <a-select-option :value="1">普通成员</a-select-option>
              </a-select>
              <template #actions>
                <CloseOutlined
                  class="deleteIcon"
                  @click="deleteItem(item.userId)"
                  v-if="item.userId !== store.getters.projectCreatorId"
                />
                <a-tooltip v-else title="创建者不能被修改">
                  <LockOutlined />
                </a-tooltip>
              </template>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue';
import type { UnwrapRef } from 'vue';
import { useStore } from 'vuex';
import ProjectDao from '@/daos/project_dao';
import UserDao from '@/daos/user_dao';

const store = useStore();
const projectDao = new ProjectDao();
const userDao = new UserDao();
const loading = ref(false);

//接口定义
interface FormState {
  members: number[];
}
interface Member {
  userId: number;
  userName: string;
  disabled?: boolean;
}

//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  memberList: {
    type: Array,
    default: []
  }
});

// 定义VNodes组件
const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true
    }
  },
  render() {
    return this.vnodes;
  }
});

//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);

//定义表单
const formRef = ref();
//项目ID获取
const projectId = store.getters.projectId;
//项目类型
const projectType = store.getters.projectType;

//初始表单内容全为undefined
const formState: UnwrapRef<FormState> = reactive({
  members: []
});

//查询用户相关
const searchInput = ref('');
const searchTypes = reactive(['用户编号', '名称', '手机号']);
const searchType = ref(searchTypes[1]); // 默认按名称搜索
const items = ref<Member[]>([]);

// 搜索用户
const searchUser = async () => {
  if (!searchInput.value && items.value.length > 0) return;
  
  loading.value = true;
  try {
    const queryParams = {
      用户编号: { userId: searchInput.value, name: null, phone: null },
      名称: { userId: null, name: searchInput.value, phone: null },
      手机号: { userId: null, name: null, phone: searchInput.value }
    }[searchType.value];
    
    const result = await userDao.findUser(
      queryParams.userId,
      queryParams.name,
      queryParams.phone,
      projectType,
      projectType === 2 ? 1 : null // 如果是课程项目，只查询教师
    );

    if (result.data.code === 200) {
      const users = result.data.data || [];
      // 已有成员ID列表
      const existingMemberIds = props.memberList.map((member: any) => member.userId);
      
      // 过滤掉已在项目中的成员
      items.value = users.filter((user: any) => !existingMemberIds.includes(user.userId));
    } else {
      message.error('获取用户列表失败');
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    message.error('搜索用户失败');
  } finally {
    loading.value = false;
  }
};

// 初始化和窗口打开时加载数据
onMounted(() => {
  if (props.modelVisible) {
    searchUser();
  }
});

watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue) {
      formState.members = [];
      searchUser();
    }
  }
);

// 添加成员
const onOk = () => {
  formRef.value
    .validate()
    .then(async () => {
      if (formState.members.length === 0) {
        message.warning('请选择要添加的成员');
        return;
      }
      
      loading.value = true;
      try {
        const result = await projectDao.upsertDeleteUsers(projectId, formState.members);
        
        if (result.data.code === 200) {
          message.success('添加成员成功');
          emit('confirm');
          emit('update:modelVisible', false);
          formRef.value.resetFields();
        } else {
          message.error(result.data.data || '添加成员失败');
        }
      } catch (error) {
        console.error('添加成员失败:', error);
        message.error('添加成员失败，请重试');
      } finally {
        loading.value = false;
      }
    })
    .catch((error) => {
      console.log('表单验证失败:', error);
    });
};

const handleCancel = () => {
  emit('update:modelVisible', false);
};
const handleOk = async () => {
  const result = await projectDao.upsertDeleteUsers(store.getters.projectId, selectedDate.value);

  message.success(result.data.data);
  emit('confirm');
  emit('update:modelVisible', false);
};

const selectedDate = ref([]);

const deleteItem = (userId) => {
  let index = selectedDate.value.findIndex((item) => item.userId === userId);
  selectedDate.value.splice(index, 1);
};
</script>
<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: space-around;
  width: 100%;
  height: 440px;
}

.item {
  display: flex;
  justify-content: space-between;
}

.item:hover {
  cursor: pointer;
  background-color: #f5f5f5aa;
}

.deleteIcon:hover {
  color: red;
}
</style>
